package com.lyh.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.db137.common.R;
import com.lyh.db137.entity.Rolemenu;
import com.lyh.db137.entity.Userrole;
import com.lyh.db137.service.RolemenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
  * @Author: 想要告诉你
  * @CreateTime: 2024/12/31 10:09
  * @Description:
  * @Version: 1.0
  */

@RestController
@CrossOrigin(origins = "*")
public class RolemenuController {
    @Autowired
    private RolemenuService rolemenuService;

    //根据菜单id查询角色菜单表的角色id
    @RequestMapping("/selectRolemenuByMenuId")
    public int selectRolemenu(long menuid) {
        QueryWrapper<Rolemenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menuid",menuid);
        List<Rolemenu> rolemenus = rolemenuService.list(queryWrapper);
        if (rolemenus.isEmpty()) {
            return 0;
        }
        return rolemenus.get(0).getRoleid();
    }

    //根据roleid查询
    @RequestMapping("/selectRolemenuByRoleId")
    public R selectRolemenu(Integer roleid) {
        QueryWrapper<Rolemenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleid",roleid);
        List<Rolemenu> rolemenus = rolemenuService.list(queryWrapper);
        return new R().addData("rolemenus", rolemenus);
    }

    //根据roleid批量删除
    @RequestMapping("/deleteRolemenuByRoleId")
    public R deleteRolemenu(Integer roleid) {
        if (roleid != null && roleid > 0){
            QueryWrapper<Rolemenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("roleid",roleid);
            rolemenuService.remove(queryWrapper);
            return new R().setCode(200).setMessage("删除成功");
        }else {
            return new R().setCode(500).setMessage("无需删除的东西");
        }

    }

    //批量新增
    @RequestMapping("/addRolemenu")
    public R addRolemenu(Integer roleid, String menuids) {
        menuids = menuids.substring(0, menuids.length() - 1); // 清除最后一个逗号
        String[] menuid = menuids.split(","); // 分割字符串
        int i = 0;
        for (String s : menuid) {
            Rolemenu rolemenu = new Rolemenu();
            rolemenu.setRoleid(roleid);
            rolemenu.setMenuid(Integer.parseInt(s));
            boolean b = rolemenuService.save(rolemenu);
            if (b){
                i++;
            }
        }
        if (i == menuid.length){
            return new R().setCode(200).setMessage("全部添加成功！");
        }else if (i != 0){
            return new R().setCode(200).setMessage(i + "个添加成功，" + (menuid.length - i) + "个添加失败！");
        }else {
            return new R().setCode(500).setMessage("全部添加失败！");
        }
    }
}
